import React, { useState, useEffect } from "react";
import { Button, Popconfirm, Space, Tag } from "antd";
import MyTemplate1 from "../../shared/myTemplate1";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import { useNavigate } from "react-router-dom";
import businesssApi from "../../../apis/businesssApi";
import { promptResult2 } from "../../../utils/common";

const BusinessManage = () => {
  useCloseLoadingOnMount();
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    key: "",
    total: 0,
  });
  const [flag, setFlag] = useState(false);
  const navigate = useNavigate();

  const columns = [
    {
      title: "店铺名称",
      dataIndex: "name2",
      key: "name2",
    },
    {
      title: "店主姓名",
      dataIndex: "managerName",
      key: "managerName",
    },
    {
      title: "电话号码",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "微信ID",
      dataIndex: "openId",
      key: "openId",
    },
    {
      title: "是否激活",
      dataIndex: "isActive",
      key: "isActive",
      render: (text) => {
        if (text == 0) {
          return <Tag>未激活</Tag>;
        } else {
          return <Tag color="green">已激活</Tag>;
        }
      },
    },
    {
      title: "是否禁用",
      dataIndex: "isBan",
      key: "isBan",
      render: (text) => {
        if (text == 0) {
          return <Tag color="green">未禁用</Tag>;
        } else {
          return <Tag color="red">已禁用</Tag>;
        }
      },
    },
    { title: "创建时间", dataIndex: "createTimeStr", key: "createTimeStr" },
    { title: "修改时间", dataIndex: "updateTimeStr", key: "updateTimeStr" },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      render: (_, record) => (
        <Space size="middle">
          <Button
            color="geekblue"
            variant="filled"
            onClick={() => handleDetail(record.id)}
          >
            详情
          </Button>
          <Popconfirm
            title="删除商家"
            description={`你确定要删除"${record.name2}"吗?`}
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button color="red" variant="filled">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 模拟API请求
  const fetchProducts = async (params = {}) => {
    setLoading(true);
    const res = await businesssApi.getBusinesssPagination({
      page: pagination.current,
      limit: pagination.pageSize,
      key: pagination.key,
    });
    setDataSource(res.data.data);
    setPagination({
      ...pagination,
      total: res.data.total,
    });
    setLoading(false);
  };

  // 监听分页对象属性变化，当变化时进行分页
  useEffect(() => {
    fetchProducts();
  }, [pagination.current]);

  useEffect(() => {
    if (flag) {
      if (pagination.current != 1) {
        setPagination({ ...pagination, current: 1 });
      } else {
        fetchProducts();
      }
    }
    setFlag(true);
  }, [pagination.pageSize, pagination.key]);

  const handleSearch = (e) => {
    setPagination({ ...pagination, key: e.target.value });
  };

  const handleDelete = async (id) => {
    await promptResult2(
      businesssApi.deleteBusinesss(id),
      () => {},
      fetchProducts
    );
  };

  const handleDetail = (id) => {
    navigate("detail/" + id);
  };

  const handleAdd = () => {
    navigate("add");
  };

  return (
    <MyTemplate1
      searchProps={{
        placeholder: "搜索店铺名称",
        onChange: handleSearch,
      }}
      addButtonProps={{
        text: "新增商家",
        onClick: handleAdd,
      }}
      columns={columns}
      dataSource={dataSource}
      loading={loading}
      pagination={pagination}
      onPageChange={(page, pageSize) => {
        setPagination({
          ...pagination,
          current: page,
          pageSize,
        });
      }}
    />
  );
};

export default BusinessManage;
